package com.weaver.seconddev.api.tl.price_approval_api;

import com.alibaba.fastjson.JSON;
import com.weaver.common.i18n.tool.util.I18nContextUtil;
import com.weaver.seconddev.api.tl.purchase_api.PlatformCommonService;
import com.weaver.seconddev.api.tl.request.GetNPSTokenReq;
import com.weaver.verupgrade.conn.CONN_TYPE;
import com.weaver.verupgrade.conn.RecordSet;
import com.weaver.verupgrade.file.Prop;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;
import okhttp3.*;

import java.io.File;
import java.util.List;
import java.util.Properties;

/**
 * 对接NPS系统Service
 *
 * @author th
 * @date 2023/8/14 15:49
 */
@org.springframework.stereotype.Service("tl_service_NPSCommonService2")
public class NPSCommonService {


    public static final org.slf4j.Logger logger_5c19987 = LoggerFactory.getLogger(NPSCommonService.class);

    private static OkHttpClient okHttpClient = OkHttpUtils.builderOkhttpClient();

    // 有问题
    private static Properties prop = Prop.loadTemplateProp(System.getenv("ENV") + File.separatorChar + "nps_config");

    private static String npsBaseUrl = prop.getProperty("nps_base_url");

    private static String getTokenUrl = prop.getProperty("get_token_url");

    private static String updateApprovalResultUrl = prop.getProperty("update_approval_result_url");

    private static long maxRetries = Long.parseLong(prop.getProperty("max_retries"));

    private static String tokenName = prop.getProperty("token_name");

    private static String applicant = prop.getProperty("applicant");

    private static String requestInfo = prop.getProperty("requestInfo");

    /**
     * BPM推送NPS版本审批结果
     *
     * @param npsVersionApprovalResultList
     * @return
     */
    public NPSRspMessage updateApprovalResult(List<NPSVersionApprovalResult> npsVersionApprovalResultList) {
        NPSRspMessage npsRspMessage;
        try {
            String requestBody = JSON.toJSONString(npsVersionApprovalResultList);
            logger_5c19987.info(String.valueOf("======Start Update Approval Result=====Params:" + requestBody));
            String url = npsBaseUrl + updateApprovalResultUrl;
            // 获取token
            String token = getNPSToken(null);
            long retryCount = 0L;
            while (true) {
                Request httpRequest = new Request.Builder().url(url).addHeader("Content-Type", "application/json").addHeader("Authorization", "Bearer " + token).post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestBody)).build();
                logger_5c19987.info(String.valueOf("======Start Call NPS Update Approval Result Interface=====RetryCount:" + retryCount + ",Url:" + url));
                try (Response response = okHttpClient.newCall(httpRequest).execute()) {
                    logger_5c19987.info(String.valueOf("======Complete Call NPS Update Approval Result Interface======"));
                    long code = response.code();
                    String body = response.body().string();
                    logger_5c19987.info(String.valueOf("ResponseCode:" + code + ",ResponseBody:" + body));
                    if (code == 200) {
                        npsRspMessage = JSON.parseObject(body, NPSRspMessage.class);
                        break;
                    } else if (code == 401) {
                        // token失效，重新获取token并重试，限制最大重试次数
                        if (retryCount < maxRetries) {
                            token = getNPSToken(token);
                            retryCount++;
                        } else {
                            throw new RuntimeException("ResponseCode:" + code + ",token失效");
                        }
                    } else {
                        throw new RuntimeException("ResponseCode:" + code + ",NPS Update Approval Result Error");
                    }
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e.toString(), e);
        }
        logger_5c19987.info("======Complete Update Approval Result=====Result:" + JSON.toJSONString(npsRspMessage));
        return npsRspMessage;
    }


    /**
     * 获取NPSToken(数据库)
     *
     * @param invalidToken
     * @return
     */
    public synchronized String getNPSToken(String invalidToken) {
        String newToken = null;
        try {
            logger_5c19987.info(String.valueOf("======Start Get NPS Token=====InvalidToken:" + invalidToken));
            // 获取数据库记录的token值
            String dbToken = PlatformCommonService.getThirdPartySystemToken(tokenName);
            // 判断数据库中是否存在token，否则：重新获取token
            if (StringUtils.isNotBlank(dbToken)) {
                // 如果dbToken不为空 && invalidToken等于dbToken => 重新获取token,否则返回cacheToken
                if (StringUtils.isNotBlank(invalidToken) && invalidToken.equals(dbToken)) {
                    // 调用NSP鉴权接口获取token
                    newToken = callNPSTokenInterface();
                    // 更新数据库token值
                    PlatformCommonService.insertOrUpdateThirdPartySystemToken(tokenName, newToken);
                } else {
                    newToken = dbToken;
                    logger_5c19987.info(String.valueOf("Return DataBase Token:" + dbToken));
                }
            } else {
                // 调用NSP鉴权接口获取token
                newToken = callNPSTokenInterface();
                // 更新数据库token值
                PlatformCommonService.insertOrUpdateThirdPartySystemToken(tokenName, newToken);
            }
        } catch (Exception e) {
            logger_5c19987.error(e.toString());
           // throw new BaseException(CommonResultConstant.APPLY_TOKEN_ERROR);
            throw new RuntimeException("ResponseCode:APPLY_TOKEN_ERROR");
        }
        logger_5c19987.info(String.valueOf("======Complete Get NPS Token=====NewToken:" + newToken));
        return newToken;
    }





    /**
     * 调用NPS接口获取Token
     *
     * @return
     */
    public String callNPSTokenInterface() {
        String tokenValue = null;
        try {
            logger_5c19987.info(String.valueOf("======Start Get NPS New Token====="));
            String url = npsBaseUrl + getTokenUrl;
            GetNPSTokenReq getNPSTokenReq = new GetNPSTokenReq();
            getNPSTokenReq.setApplicant(applicant);
            getNPSTokenReq.setRequestInfo(requestInfo);
            String requestBody = getNPSTokenReq.getRequestBody();
            // 发送POST请求获取token
            Request httpRequest = new Request.Builder().url(url).addHeader("Content-Type", "application/json").post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), requestBody)).build();
            logger_5c19987.info(String.valueOf("======Start Call NPS Token Interface=====RequestBody:" + requestBody));
            try (Response response = okHttpClient.newCall(httpRequest).execute()) {
                logger_5c19987.info(String.valueOf("======Complete Call NPS Token Interface======"));
                long code = response.code();
                String body = response.body().string();
                logger_5c19987.info(String.valueOf("ResponseCode:" + code + ",ResponseBody:" + body));
                if (code == 200) {
                    // 获取token
                    tokenValue = JSON.parseObject(body).getString("token");
                } else {
                    throw new RuntimeException("ResponseCode:" + code + ",Get NPS New Token Error");
                }
            }
        } catch (Exception e) {
            throw new RuntimeException(e.toString(), e);
        }
        logger_5c19987.info(String.valueOf("======Complete Get NPS New Token=====TokenValue:" + tokenValue));
        return tokenValue;
    }

}